package com.xy.csdn.cfg;

import com.xy.csdn.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.IOException;
import java.net.URI;

/**
 * 自定义Http响应异常处理器
 * @author chuanjieyang
 * @since May 23, 2019 10:49:33 AM
 */
public class CustomErrorHandler implements ResponseErrorHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomErrorHandler.class);

    /**
     * 返回false表示不管response的status是多少都返回没有错
     * 这里可以自己定义那些status code你认为是可以抛Error
     * Indicate whether the given response has any errors.
     * <p>Implementations will typically inspect the
     * {@link ClientHttpResponse#getStatusCode() HttpStatus} of the response.
     *
     * @param response the response to inspect
     * @return {@code true} if the response indicates an error; {@code false} otherwise
     * @throws IOException in case of I/O errors
     */
    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        return response.getStatusCode().value() != 200 && response.getStatusCode().value() !=302;
    }

    /**
     * 这里面可以实现你自己遇到了Error进行合理的处理
     * Handle the error in the given response.
     * <p>This method is only called when {@link #hasError(ClientHttpResponse)}
     * has returned {@code true}.
     *
     * @param response the response with the error
     * @throws IOException in case of I/O errors
     */
    @Override
    public void handleError(ClientHttpResponse response) throws IOException {

    }

    /**
     * 替代上面的方法
     * Alternative to {@link #handleError(ClientHttpResponse)} with extra
     * information providing access to the request URL and HTTP method.
     *
     * @param url      the request URL
     * @param method   the HTTP method
     * @param response the response with the error
     * @throws IOException in case of I/O errors
     * @since 5.0
     */
    @Override
    public void handleError(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
        LOGGER.error("=======================ERROR============================");
        LOGGER.error("DateTime：{}", DateUtil.generateTimeFormatter(response.getHeaders().getDate(),"yyyy-MM-dd HH:mm:ss"));
        LOGGER.error("HOST:{},URI：{}", url.getHost(),url.getPath());
        LOGGER.error("Method：{}", method.name());
        LOGGER.error("Exception：{}", response.getStatusCode());
        LOGGER.error("========================================================");
    }
}
